/**
 * 
 */
package com.yinhai.activity;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;
import android.preference.PreferenceManager;
import android.provider.Contacts.People;
import android.provider.ContactsContract;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SimpleAdapter;
import android.widget.Toast;

import com.androidquery.AQuery;
import com.androidquery.callback.AjaxCallback;
import com.androidquery.callback.AjaxStatus;
import com.cmcc.groupcontacts.numbersearch.activity.NumberSearchActivity;
import com.lz.util.Utils;
import com.yinhai.adapter.ViewPagerAdapter;
import com.yinhai.asynctask.ContactDownloadTask;
import com.yinhai.cfg.AppConfig;
import com.yinhai.cfg.LoginConfig;
import com.yinhai.cfg.LoginConfigUtil;
import com.yinhai.constant.Contact;
import com.yinhai.constant.UrlConstant;
import com.yinhai.contacts.util.ContactsUtils;
import com.yinhai.dao.ContactUserDaoImpl;
import com.yinhai.model.ContactsUser;
import com.yinhai.service.ContactUserServiceImpl;
import com.yinhai.util.DateUtil;
import com.yinhai.util.InternetUtils;
import com.yinhai.util.PhoneSearchFunction;
import com.yinhai.util.PinYinUtil;
import com.yinhai.util.Util;
import com.yinhai.view.CustomProgressDialog;

/**
 * @author Juyon
 * 
 */
public class MoreAppFragment extends Fragment implements OnClickListener, OnPageChangeListener {
    // 定义ViewPager对象
    private ViewPager viewPager;
    
    private int viewCount = 2;
    
    // 定义ViewPager适配器
    private ViewPagerAdapter vpAdapter;
    
    // 定义一个ArrayList来存放View
    private ArrayList<View> views;
    
    // 引导图片资源
    // private static final int[] pics = { R.drawable.guide1,
    // R.drawable.guide2};
    
    // 底部小点的图片
    private ImageView[] points;
    
    // 记录当前选中位置
    private int currentIndex;
    
    private Context context;
    
    private LoginConfig log = null;
    
    private SharedPreferences sharedPreferences;
    
    CustomProgressDialog downloadProgressDialog;
    
    private AQuery aq = null;
    
    AlertDialog dialog = null;
    
    private int progressCount = 0;
    
    private boolean localFlag = false;
    
    private LocalMyHandler localHandler;
    
    private int allTotal = 0;
    
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
        View view = inflater.inflate(R.layout.main_more_app, null);
        /*
         * View contact_asynchronized_img = view .findViewById(R.id.contact_asynchronized_img);
         */
        View contact_asynchronized_text = view.findViewById(R.id.contact_asynchronized_text);
        context = this.getActivity();
        // View system_setup_img = view.findViewById(R.id.system_setup_img);
        View system_setup_text = view.findViewById(R.id.system_setup_text);
        
        log = LoginConfigUtil.getConfig(getActivity());
        /*
         * system_setup_img.setOnClickListener(new OnClickListener() {
         * 
         * @Override public void onClick(View arg0) { // TODO Auto-generated method stub Intent intent = new
         * Intent(getActivity(), SystemSetupMainActivity.class); startActivity(intent); } });
         */
        /**
         * 系统设置
         */
        system_setup_text.setOnClickListener(new OnClickListener() {
            
            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                Intent intent = new Intent(getActivity(), SystemSetupMainActivity.class);
                startActivity(intent);
            }
        });
        aq = new AQuery(context);
        
        /**
         * 单位通讯录同步
         */
        contact_asynchronized_text.setOnClickListener(new OnClickListener() {
            
            @Override
            public void onClick(View arg0) {
                
                // 判断网络连接
                if (InternetUtils.isConnect(context)) {
                    if (sharedPreferences.contains("onLineUpdateTime")) {
                        long time = sharedPreferences.getLong("onLineUpdateTime", 0L);
                        if (System.currentTimeMillis() - time < 1 * 60 * 1000) {
                            Util.showMsg(getActivity(), "请勿频繁更新，间隔一分钟后再试");
                            return;
                        }
                    }
                    String contactGroupVersion = sharedPreferences.getString("contactGroupVersion", "");
                    SharedPreferences preferences1 =
                        context.getSharedPreferences(AppConfig.LOGIN_CONFIG, Context.MODE_PRIVATE);
                    String phone = preferences1.getString("name", "");
                    aq.ajax(UrlConstant.LOCAL_URI + UrlConstant.CHECK_CONTACTS_VERSION + "?phone=" + phone
                        + "&version=" + contactGroupVersion, JSONObject.class, new AjaxCallback<JSONObject>() {
                        @Override
                        public void callback(String url, JSONObject object, AjaxStatus status) {
                            if (object != null) {
                                try {
                                    Editor editor = sharedPreferences.edit();
                                    editor.putLong("onLineUpdateTime", System.currentTimeMillis());
                                    editor.putString("onLineContactLastUpdateTime",
                                        DateUtil.dateFormatString(new Date(), DateUtil.DAY_TIME_FORMATE));
                                    editor.commit();
                                    if (object.getBoolean("success")) {
                                        initOnlineData(LoginConfigUtil.getConfig(getActivity()).getUsername());
                                    } else {
                                        Toast.makeText(context, "当前已经是最新版本无需更新!", Toast.LENGTH_SHORT).show();
                                    }
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                    Toast.makeText(context, "系统异常:" + e.getMessage(), Toast.LENGTH_SHORT).show();
                                }
                                
                            } else {
                                Toast.makeText(context, "网络错误!Error:" + status.getCode(), Toast.LENGTH_SHORT).show();
                            }
                        }
                    });
                } else {
                    Toast.makeText(context, "网络不可以用请设置网络!", Toast.LENGTH_SHORT).show();
                }
            }
        });
        
        /**
         * 本地通讯录同步
         * 
         */
        View contact_bdtxl = view.findViewById(R.id.contact_bdtxl);
        contact_bdtxl.setOnClickListener(new OnClickListener() {
            
            @Override
            public void onClick(View v) {
                localFlag = false;
                HandlerThread myThread = new HandlerThread("myHandlerThread");
                myThread.start();
                localHandler = new LocalMyHandler(myThread.getLooper());
                localHandler.post(new Runnable() {
                    
                    @Override
                    public void run() {
                        while (!localFlag) {
                            if (customProgressDialog != null) {
                                if (progressCount < 99) {
                                    progressCount = progressCount + 1;
                                    // progressDialog.setProgress(progressCount);
                                    try {
                                        Thread.sleep(500);
                                    } catch (InterruptedException e) {
                                        e.printStackTrace();
                                    }
                                }
                            } else {
                                localFlag = true;
                            }
                            
                        }
                    }
                    
                });
                new LocalContactAsyncTask().execute();
            }
        });
        
        /**
         * 个人设置
         */
        View idsetting = view.findViewById(R.id.idsetting);
        idsetting.setOnClickListener(OnSettingClick);
        // 初始化组件
        // initView(view);
        
        View layoutfx = view.findViewById(R.id.layoutfx);
        layoutfx.setOnClickListener(OnLayoutFxClick);
        // 初始化数据
        initData(inflater, view);
        return view;
    }
    
    OnClickListener OnSettingClick = new OnClickListener() {
        
        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            Intent it = new Intent(getActivity(), SettingActivity.class);
            startActivity(it);
        }
    };
    
    OnClickListener OnLayoutFxClick = new OnClickListener() {
        
        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            dialog = Utils.showSetMsgDialog(getActivity(), new OnClickListener() {
                
                @Override
                public void onClick(View arg0) {
                    Intent it = new Intent(getActivity(), MsgQFActivity.class);
                    it.putExtra("IsFx", 1);
                    startActivity(it);
                    dialog.cancel();
                }
            }, new OnClickListener() {
                
                @Override
                public void onClick(View arg0) {
                    
                    Intent intent = new Intent(Intent.ACTION_SENDTO);
                    intent.setData(Uri.parse("smsto:" + ""));
                    intent.putExtra("sms_body", MsgQFActivity.NameFX);
                    startActivity(intent);
                    dialog.cancel();
                }
            });
            
        }
    };
    
    private void initOnlineData(String phone) {
        ContactUserServiceImpl c = new ContactUserServiceImpl(this.getActivity());
        c.initOnlineContact(phone);
        createProcessDialog();
    }
    
    public ArrayList<HashMap<String, Object>> buildView(int i) {
        ArrayList<HashMap<String, Object>> lstImageItem = new ArrayList<HashMap<String, Object>>();
        if (i == 0) {
            HashMap<String, Object> map1 = new HashMap<String, Object>();
            map1.put("ItemImage", R.drawable.function_1);// 添加图像资源的ID
            map1.put("ItemText", "集团短信群发");// 按序号做ItemText
            map1.put("activity", MsgQFActivity.class);
            HashMap<String, Object> map2 = new HashMap<String, Object>();
            map2.put("ItemImage", R.drawable.function_2);// 添加图像资源的ID
            map2.put("ItemText", "节日短信自动回复");// 按序号做ItemText
            map2.put("activity", IsDXZDHFActivity.class);
            HashMap<String, Object> map3 = new HashMap<String, Object>();
            map3.put("ItemImage", R.drawable.function_3);// 添加图像资源的ID
            map3.put("ItemText", "本机通讯录云备份");// 按序号做ItemText
            map3.put("activity", BFContactsPhoneActivity.class);
            // HashMap<String, Object> map4 = new HashMap<String, Object>();
            // try {
            // map4 = new HashMap<String, Object>();
            // map4.put("ItemImage", R.drawable.function_4);// 添加图像资源的ID
            // map4.put("ItemText", "防打扰");// 按序号做ItemText
            // // map4.put("activity", FirewallTabActivity.class);// 按序号做ItemText
            // } catch (Exception e) {
            // e.printStackTrace();
            // }
            HashMap<String, Object> map5 = new HashMap<String, Object>();
            map5.put("ItemImage", R.drawable.function_5);// 添加图像资源的ID
            map5.put("ItemText", "云笔记");// 按序号做ItemText
            map5.put("activity", CloudNoteActivity.class);
            HashMap<String, Object> map6 = new HashMap<String, Object>();
            map6.put("ItemImage", R.drawable.function_6);// 添加图像资源的ID
            map6.put("ItemText", "便捷充值");// 按序号做ItemText
            map6.put("activity", WebViewCZActivity.class);
            Bundle b = new Bundle();
            b.putCharSequence("title", "便捷充值");
            b.putCharSequence("url", "http://wap.10086.cn/czjf/czjf.jsp");
            map6.put("bundle", b);
            HashMap<String, Object> map7 = new HashMap<String, Object>();
            map7.put("ItemImage", R.drawable.function_7);// 添加图像资源的ID
            map7.put("ItemText", "主题皮肤");// 按序号做ItemText
            map7.put("activity", ThemeActivity.class);//
            HashMap<String, Object> map8 = new HashMap<String, Object>();
            map8.put("ItemImage", R.drawable.function_8);// 添加图像资源的ID
            map8.put("ItemText", "软件升级");// 按序号做ItemText
            map8.put("activity", UpdateActivity.class);
            HashMap<String, Object> map9 = new HashMap<String, Object>();
            map9.put("ItemImage", R.drawable.function_9);// 添加图像资源的ID
            map9.put("ItemText", "常用电话");// 按序号做ItemText
            map9.put("activity", NumberSearchActivity.class);
            lstImageItem.add(map1);
            lstImageItem.add(map2);
            lstImageItem.add(map3);
            // lstImageItem.add(map4);
            lstImageItem.add(map5);
            lstImageItem.add(map6);
            lstImageItem.add(map7);
            lstImageItem.add(map8);
            lstImageItem.add(map9);
        } else if (i == 1) {
            
            HashMap<String, Object> map2 = new HashMap<String, Object>();
            map2.put("ItemImage", R.drawable.function_10);// 添加图像资源的ID
            map2.put("ItemText", "应用推荐");// 按序号做ItemText
            map2.put("activity", AppSuggestActivity.class);
            // HashMap<String, Object> map3 = new HashMap<String, Object>();
            // map3.put("ItemImage", R.drawable.function_11);// 添加图像资源的ID
            // map3.put("ItemText", "本机联系人去重");// 按序号做ItemText
            // map3.put("activity", "");
            // map3.put("clearSameContacts", "clearSameContacts");
            // HashMap<String, Object> map4 = new HashMap<String, Object>();
            // map4.put("ItemImage", R.drawable.function_12);// 添加图像资源的ID
            // map4.put("ItemText", "SIM卡联系人导入");// 按序号做ItemText
            // map4.put("activity", "");
            // map4.put("sim", "sim");
            HashMap<String, Object> map5 = new HashMap<String, Object>();
            map5.put("ItemImage", R.drawable.function_13);// 添加图像资源的ID
            map5.put("ItemText", "软件建议");// 按序号做ItemText
            map5.put("activity", FeedbackActivity.class);
            HashMap<String, Object> map6 = new HashMap<String, Object>();
            map6.put("ItemImage", R.drawable.function_14);// 添加图像资源的ID
            map6.put("ItemText", "扫一扫");// 按序号做ItemText
            map6.put("activity", EWMActivity.class);// 按序号做ItemText
            HashMap<String, Object> map7 = new HashMap<String, Object>();
            /*
             * map7.put("ItemImage", R.drawable.function_15);// 添加图像资源的ID map7.put("ItemText", "帮助");// 按序号做ItemText
             * map7.put("activity", WebViewActivity.class);
             */
            /*
             * Bundle b = new Bundle(); b.putCharSequence("title", "帮助"); b.putCharSequence("url",
             * "file:///android_asset/help.html"); map7.put("bundle", b);
             */
            map7.put("ItemImage", R.drawable.function_15);// 添加图像资源的ID
            map7.put("ItemText", "帮助");// 按序号做ItemText
            map7.put("activity", WebViewCZActivity.class);
            Bundle b = new Bundle();
            b.putCharSequence("title", "帮助");
            b.putCharSequence("url", "file:///android_asset/help.html");
            map7.put("bundle", b);
            
            HashMap<String, Object> map8 = new HashMap<String, Object>();
            map8.put("ItemImage", R.drawable.function_16);// 添加图像资源的ID
            map8.put("ItemText", "关于");// 按序号做ItemText
            map8.put("activity", AboutActivity.class);
            // lstImageItem.add(map1);
            lstImageItem.add(map2);
            // lstImageItem.add(map3);
            // lstImageItem.add(map4);
            lstImageItem.add(map5);
            lstImageItem.add(map6);
            lstImageItem.add(map7);
            lstImageItem.add(map8);
        }
        return lstImageItem;
    }
    
    /**
     * 初始化数据
     */
    private void initData(LayoutInflater inflater, View view) {
        // 实例化ArrayList对象
        views = new ArrayList<View>();
        
        // 实例化ViewPager
        viewPager = (ViewPager)view.findViewById(R.id.viewpager);
        
        // 实例化ViewPager适配器
        vpAdapter = new ViewPagerAdapter(views);
        // 定义一个布局并设置参数
        GridView view1 = (GridView)inflater.inflate(R.layout.more_app_gridview1, null);
        GridView view2 = (GridView)inflater.inflate(R.layout.more_app_gridview1, null);
        
        // 生成适配器的ImageItem <====> 动态数组的元素，两者一一对应
        SimpleAdapter saImageItems1 = new SimpleAdapter(this.getActivity(), // 没什么解释
            buildView(0),// 数据来源
            R.layout.more_app_gridview_item1,// night_item的XML实现
            
            // 动态数组与ImageItem对应的子项
            new String[] {"ItemImage", "ItemText"},
            
            // ImageItem的XML文件里面的一个ImageView,两个TextView ID
            new int[] {R.id.ItemImage1, R.id.ItemText1});
        // 生成适配器的ImageItem <====> 动态数组的元素，两者一一对应
        SimpleAdapter saImageItems2 = new SimpleAdapter(this.getActivity(), // 没什么解释
            buildView(1),// 数据来源
            R.layout.more_app_gridview_item1,// night_item的XML实现
            // 动态数组与ImageItem对应的子项
            new String[] {"ItemImage", "ItemText"},
            
            // ImageItem的XML文件里面的一个ImageView,两个TextView ID
            new int[] {R.id.ItemImage1, R.id.ItemText1});
        // 添加并且显示
        view1.setAdapter(saImageItems1);
        // 添加并且显示
        view2.setAdapter(saImageItems2);
        // 添加消息处理
        view1.setOnItemClickListener(new ItemClickListener());
        // 添加消息处理
        view2.setOnItemClickListener(new ItemClickListener());
        views.add(view1);
        views.add(view2);
        // }
        
        // 设置数据
        // 前面的views中没有数据 在前面的循环中才插入数据 而此时vpAdapter中已经有数据说明
        // 初始化adapter的时候 参数传递是传引用
        viewPager.setAdapter(vpAdapter);
        // 设置监听
        viewPager.setOnPageChangeListener(this);
        
        // 初始化底部小点
        initPoint(view);
    }
    
    /**
     * 初始化底部小点
     */
    private void initPoint(View view) {
        LinearLayout linearLayout = (LinearLayout)view.findViewById(R.id.linearLayout);
        
        points = new ImageView[viewCount];
        
        // 循环取得小点图片
        for (int i = 0; i < viewCount; i++) {
            // 得到一个LinearLayout下面的每一个子元素
            points[i] = (ImageView)linearLayout.getChildAt(i);
            // 默认都设为灰色
            points[i].setEnabled(false);
            // 给每个小点设置监听
            points[i].setOnClickListener(this);
            // 设置位置tag，方便取出与当前位置对应
            points[i].setTag(i);
        }
        
        // 设置当面默认的位置
        currentIndex = 0;
        // 设置为白色，即选中状态
        points[currentIndex].setEnabled(true);
    }
    
    // 当AdapterView被单击(触摸屏或者键盘)，则返回的Item单击事件
    class ItemClickListener implements OnItemClickListener {
        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
            // 在本例中arg2=arg3
            HashMap<String, Object> item = (HashMap<String, Object>)arg0.getItemAtPosition(arg2);
            if (item.containsKey("activity")) {
                if (item.containsKey("sim")) {
                    if ("sim".equals("sim")) {
                        new AlertDialog.Builder(context).setTitle("SIM卡联系人导入")
                            .setMessage("该操作会将SIM卡中的联系人呢导入手机，是否继续?")
                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int which) {
                                    // 获取SIM
                                    Uri uri = Uri.parse("content://icc/adn");
                                    Cursor cursor = context.getContentResolver().query(uri, null, null, null, null);
                                    int count = cursor.getCount();
                                    while (cursor.moveToNext()) {
                                        String id = cursor.getString(cursor.getColumnIndex(People._ID));
                                        String name = cursor.getString(cursor.getColumnIndex(People.NAME));
                                        String phoneNumber = cursor.getString(cursor.getColumnIndex(People.NUMBER));
                                        ContentResolver resolver = context.getContentResolver();
                                        Uri contacts = Uri.parse("content://com.android.contacts/raw_contacts");
                                        ContentValues values = new ContentValues();
                                        // 向raw_contacts插入一条除了ID之外,
                                        // 其他全部为NULL的记录, ID是自动生成的
                                        Uri uri2 = resolver.insert(uri, values);
                                        if (uri2 == null) {
                                            continue;
                                        }
                                        long contactId = ContentUris.parseId(uri2);
                                        // 添加联系人姓名
                                        uri = Uri.parse("content://com.android.contacts/data");
                                        values.put("raw_contact_id", contactId);
                                        values.put("data2", name);
                                        values.put("mimetype", "vnd.android.cursor.item/name");
                                        resolver.insert(uri, values);
                                        // 添加联系人电话
                                        values.clear(); // 清空上次的数据
                                        values.put("raw_contact_id", contactId);
                                        values.put("data1", phoneNumber);
                                        values.put("data2", "2");
                                        values.put("mimetype", "vnd.android.cursor.item/phone_v2");
                                        resolver.insert(uri, values);
                                    }
                                    cursor.close();
                                    new AlertDialog.Builder(context).setTitle("SIM卡联系人导入")
                                        .setMessage("成功导入" + count + "条联系人信息")
                                        .setPositiveButton("确定", null)
                                        .show();
                                }
                            })
                            .setNegativeButton("取消", null)
                            .show();
                    }
                } else if (item.containsKey("clearSameContacts")) {
                    LinkedList<String> nameList =
                        ContactsUtils._getContactsPhoneOrName(getActivity().getContentResolver(), 0);
                    LinkedList<String> phoneList =
                        ContactsUtils._getContactsPhoneOrName(getActivity().getContentResolver(), 1);
                    List<String> nameList1 = ContactsUtils.CheckOverlap(nameList);
                    List<String> phoneList1 = ContactsUtils.CheckOverlap(phoneList);
                    if (nameList1.size() == 0 && phoneList1.size() == 0) {
                        Toast.makeText(context, "无重复联系人", Toast.LENGTH_SHORT).show();
                    } else {
                        Intent intent = new Intent(getActivity(), ContactsSameListActivity.class);
                        startActivity(intent);
                    }
                } else {
                    Intent intent = new Intent(getActivity(), (Class<?>)item.get("activity"));
                    if (item.containsKey("bundle")) {
                        intent.putExtras((Bundle)item.get("bundle"));
                    }
                    startActivity(intent);
                }
                
            }
            
        }
    }
    
    // ProgressDialog progressDialog = null;
    CustomProgressDialog customProgressDialog = null;
    
    private class LocalContactAsyncTask extends AsyncTask<Integer, Integer, Integer> {
        @Override
        protected void onPostExecute(Integer result) {
            // TODO Auto-generated method stub
            super.onPostExecute(result);
            customProgressDialog.setProgress(100);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            customProgressDialog.dismiss();
            customProgressDialog = null;
            progressCount = 0;
            if (1 == result) {
                Toast.makeText(context, "同步0个本地联系人,请设置读取联系人权限或者本机联系人数量为0", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(context, "加载本地通讯联系人成功,加载了" + allTotal + "个本地联系人", Toast.LENGTH_SHORT).show();
                
            }
        }
        
        @Override
        protected void onProgressUpdate(Integer... values) {
            // TODO Auto-generated method stub
            if (progressCount < 99) {
                progressCount = progressCount + 1;
                customProgressDialog.setProgress(progressCount);
            }
            super.onProgressUpdate(values);
        }
        
        @Override
        protected void onPreExecute() {
            // TODO Auto-generated method stub
            // super.onPreExecute();
            customProgressDialog = new CustomProgressDialog(getActivity());
            customProgressDialog.setMessage("正在同步本机联系人信息");
            customProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            customProgressDialog.setCancelable(false);
            customProgressDialog.setProgress(0);
            customProgressDialog.show();
            // progressDialog = ProgressDialog.show(getActivity(), "", "正在同步本机联系人信息...");
            // progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        }
        
        @Override
        protected Integer doInBackground(Integer... arg0) {
            progressCount = progressCount + 1;
            customProgressDialog.setProgress(progressCount);
            this.publishProgress(progressCount);
            // try {
            // Thread.sleep(2000);
            // } catch (InterruptedException e) {
            // e.printStackTrace();
            // }
            ContactUserDaoImpl contactUserDao = new ContactUserDaoImpl(context);
            contactUserDao.execSql("delete from contact_user where type='" + Contact.CONTACT_TYPE_LOCAL + "'",
                new String[] {});
            
            // ContactUserServiceImpl c = new ContactUserServiceImpl(context);
            // false表示同步联系人失败
            boolean flag = init(customProgressDialog);
            
            localFlag = true;
            if (!flag) {
                return 1;
            }
            
            return 0;
        }
        
    }
    
    private boolean init(CustomProgressDialog pd) {
        boolean flag = true;
        try {
            ContentResolver contentResolver = context.getContentResolver();
            Uri uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI; // 联系人Uri；
            // 查询的字段
            String[] projection =
                {ContactsContract.CommonDataKinds.Phone._ID, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
                    ContactsContract.CommonDataKinds.Phone.DATA1, "sort_key",
                    ContactsContract.CommonDataKinds.Phone.CONTACT_ID, ContactsContract.CommonDataKinds.Phone.PHOTO_ID,
                    ContactsContract.CommonDataKinds.Phone.LOOKUP_KEY,
                    ContactsContract.CommonDataKinds.Phone.CONTACT_ID};
            // 按照sort_key升序查詢
            Cursor cursor = contentResolver.query(uri, projection, null, null, "sort_key COLLATE LOCALIZED asc");
            List<ContactsUser> list = new ArrayList<ContactsUser>();
            ContactsUser cuser = null;
            
            Map<String, String> mapTreadId = new HashMap<String, String>();
            int total = cursor.getCount();
            allTotal = total;
            if (total == 0) {
                pd.setProgress(100);
            }
            int ont = 10000 / total;
            Log.i("xxdds", System.currentTimeMillis() + "");
            if (cursor != null && cursor.getCount() > 0) {
                cursor.moveToFirst(); // 游标移动到第一项
                for (int i = 0; i < cursor.getCount(); i++) {
                    cursor.moveToPosition(i);
                    String thread_id = cursor.getString(7);
                    if (mapTreadId.get(thread_id) == null) {
                        mapTreadId.put(thread_id, "xx");
                    } else {
                        continue;
                    }
                    String name = cursor.getString(1);
                    String number = cursor.getString(2).trim().replaceAll(" ", "");
                    ContactsUser user = new ContactsUser();
                    user.setTelPhone(number);
                    user.setName(name);
                    user.setType(Contact.CONTACT_TYPE_LOCAL);
                    user.setGroupId(Contact.LOCAL_CONTACT_GROUP_ID);
                    user.setGroupName(Contact.LOCAL_CONTACT_GROUP_NAME);
                    user.setShortNum(PhoneSearchFunction.GetSearchStr(name));
                    user.setNameSimple(PinYinUtil.getString2Num(PinYinUtil.getFirstSpell(name)));
                    user.setFirstpy(PinYinUtil.getFirstSpell(name));
                    user.setFullpy(PinYinUtil.getFullSpell(name));
                    user.setFullpynum(PinYinUtil.getString2Num(PinYinUtil.getFullSpell(name)));
                    user.setFullpysep(PinYinUtil.getFullSpellSep(name));
                    user.setFullpynumsep(PinYinUtil.getString2Num(PinYinUtil.getFullSpellSep(name)));
                    list.add(user);
                    // Long id = contactUserDao.insert(user);
                    ContactUserServiceImpl.phoneNames.put(number, name);
                    ContactUserServiceImpl.phoneThreads.put(number, thread_id);
                    pd.setProgress(Math.round((ont * i) / 100));
                }
                cursor.close();
                SQLiteDatabase db = this.context.openOrCreateDatabase("im.db", Context.MODE_PRIVATE, null);
                db.beginTransaction();
                for (int i = 0; i < list.size(); i++) {
                    cuser = list.get(i);
                    db.execSQL("INSERT INTO contact_user(name, tel_phone, type,group_id,group_name,userid,short_num,first_py,name_simple,full_py,full_py_num,full_py_sep,full_py_num_sep,usort)"
                        + " values(?, ?, ?,?,?,?,?,?,?,?,?,?,?,?)",
                        new Object[] {cuser.getName(), cuser.getTelPhone(), cuser.getType(), cuser.getGroupId(),
                            cuser.getGroupName(), cuser.getUserid(), cuser.getShortNum(), cuser.getFirstpy(),
                            cuser.getNameSimple(), cuser.getFullpy(), cuser.getFullpynum(), cuser.getFullpysep(),
                            cuser.getFullpynumsep(), cuser.getUsort()
                        
                        });
                }
                db.setTransactionSuccessful();
                db.endTransaction();
                // if(db !=null){
                db.close();
                // }
                
            } else {
                flag = false;
            }
        } catch (Exception e) {
            e.printStackTrace();
            flag = false;
        }
        
        // Toast.makeText(context, "加载本地通讯录成功共同步"+total+"个本地联系人", Toast.LENGTH_SHORT).show();
        return flag;
    }
    
    private class LocalContactThread extends Thread {
        
    }
    
    /**
     * 当滑动状态改变时调用
     */
    @Override
    public void onPageScrollStateChanged(int arg0) {
        
    }
    
    /**
     * 当当前页面被滑动时调用
     */
    
    @Override
    public void onPageScrolled(int arg0, float arg1, int arg2) {
        
    }
    
    /**
     * 当新的页面被选中时调用
     */
    
    @Override
    public void onPageSelected(int position) {
        // 设置底部小点选中状态
        setCurDot(position);
    }
    
    /**
     * 通过点击事件来切换当前的页面
     */
    @Override
    public void onClick(View v) {
        int position = (Integer)v.getTag();
        setCurView(position);
        setCurDot(position);
    }
    
    /**
     * 设置当前页面的位置
     */
    private void setCurView(int position) {
        // 排除异常情况
        if (position < 0 || position >= viewCount) {
            return;
        }
        viewPager.setCurrentItem(position);
    }
    
    /**
     * 设置当前的小点的位置
     */
    private void setCurDot(int positon) {
        // 排除异常情况
        if (positon < 0 || positon > viewCount - 1 || currentIndex == positon) {
            return;
        }
        points[positon].setEnabled(true);
        points[currentIndex].setEnabled(false);
        
        currentIndex = positon;
    }
    
    @SuppressWarnings("unchecked")
    Handler handler = new android.os.Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what==1) {
                
            }
        }
    };
    
    /**
     * 创建更新联系人对话框
     */
    private void createProcessDialog() {
        downloadProgressDialog = new CustomProgressDialog(this.context);
        downloadProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        downloadProgressDialog.setMessage("Loading...");
        downloadProgressDialog.setCancelable(false);
        downloadProgressDialog.setProgress(0);
        downloadProgressDialog.show();
        ContactDownloadTask task = new ContactDownloadTask(this.context, this.downloadProgressDialog, handler);
        List list = new ArrayList();
        task.execute(list);
    }
    
    class LocalMyHandler extends Handler {
        
        public LocalMyHandler(Looper looper) {
            super(looper);
        }
        
        @Override
        public void handleMessage(Message msg) {
        }
    }
}
